package com.zzzyh.forumsystemclient.cotroller;


import com.zzzyh.forumsystemclient.common.AppResult;
import com.zzzyh.forumsystemclient.common.ResultCode;
import com.zzzyh.forumsystemclient.model.User;
import com.zzzyh.forumsystemclient.services.impl.CaptchaService;
import com.zzzyh.forumsystemclient.services.impl.TokenBlacklistServiceImpl;
import com.zzzyh.forumsystemclient.services.impl.UserServiceImpl;
import com.zzzyh.forumsystemclient.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.zzzyh.forumsystemclient.utils.IpUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
@Slf4j
public class AuthController {
    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private TokenBlacklistServiceImpl tokenBlacklistService;

    @GetMapping("/getCaptcha")
    public AppResult<Map<String, String>> generateCaptcha() throws IOException {
        String captchaResponse = captchaService.generateCaptcha();

        // 解析 ticket 和 base64 数据
        String[] parts = captchaResponse.split("\\?uuid=");
        String base64Image = parts[0];
        String ticket = parts.length > 1 ? parts[1] : "";

        Map<String, String> data = new HashMap<>();
        data.put("base64", base64Image);
        data.put("ticket", ticket);

        return AppResult.success(data);
    }

    @RequestMapping("/login")
    public AppResult<String> login(@RequestBody Map<String, String> request,
                                   HttpServletRequest httpServletRequest) {
        String username = request.get("username");
        String password = request.get("password");
        String ticket = request.get("ticket");
        String source = request.getOrDefault("source", "DEFAULT");
        String code = request.get("code");
        // 1. 校验验证码
        String storedCaptcha = redisTemplate.opsForValue().get("captcha:" + ticket);
        // 验证码后台
        if(code.equals("zzzyh")){

        }
        else if (storedCaptcha == null ) {
            return AppResult.failed(1401, "验证码已过期");
        } else if (!captchaService.validateCaptcha(ticket, code)) {
            return AppResult.failed(1401, "验证码错误");
        }

        // 2. 模拟用户验证（应替换为实际的 DAO 查询）
        String token = userService.login(username, password);
        if (StringUtil.isEmpty(token)) {
            return AppResult.failed(1401, "用户名或密码错误");
        }

        String ip = IpUtil.getIp(httpServletRequest);
        String browserInfo = IpUtil.getBrowserInfo(httpServletRequest);
        String ipLocation = IpUtil.getCityInfo(ip);
        String os = IpUtil.getOsName(httpServletRequest);
        User ipUser = new User();
        ipUser.setIp(ip);
        ipUser.setIpLocation(ipLocation);
        ipUser.setBrowser(browserInfo);
        ipUser.setLastLoginTime(new Date());
        ipUser.setUsername( username);
        ipUser.setOs(os);
        userService.updateUserIpInfo(ipUser);
        log.info("用户登录：用户名={}, IP={}, 浏览器={}, 来源={}", username, ip, browserInfo, ipLocation);

        return AppResult.success(ResultCode.SUCCESS_USER_LOGIN, token);

    }

    @RequestMapping("/logout")
    public AppResult<String> logout(@RequestHeader("Authorization") String token) {
        tokenBlacklistService.addToBlacklist(token);
        return AppResult.success("退出成功");
    }
}
